//
//  CameraViewController.m
//  Version1.0_RectiveCocoa
//
//  Created by 吴可高 on 2018/1/21.
//  Copyright © 2018年 吴可高. All rights reserved.
//

#import "CameraViewController.h"
#import "QKEasyAlbumController.h"
#import <AVFoundation/AVFoundation.h>
#import "CameraBottomView.h"

@interface CameraViewController ()<UIGestureRecognizerDelegate>
//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic,strong) AVCaptureDevice * captureDevice;
//输入设备
@property(nonatomic,strong) AVCaptureDeviceInput * input;
//输入图片
@property(nonatomic,strong) AVCaptureStillImageOutput * imageOutput;
//把输入输出结合在一起，并开始启动捕获设备
@property(nonatomic,strong) AVCaptureSession * session;
//图像预览层 显示铺捉图像
@property(nonatomic,strong) AVCaptureVideoPreviewLayer * videoPreviewPlayer;

@property(nonatomic,strong) UIImage * image;
@property(nonatomic,strong) UIImageView * imageView;
//optional_item
@property(nonatomic,strong) NSMutableArray * items;
@property(nonatomic,strong) NSMutableArray * itemContainers;
@property(nonatomic,strong) CameraBottomView * cameraBottomView;
@end

@implementation CameraViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

-(void)initializeNavigationBar{
    self.view.backgroundColor = UIColorFromRGB(0x151724);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeNavigationBar];
    [self cameraConfiguation];
    [self configurationOptionalViews];
    [self viewlayoutSubViews];
}

-(void)configurationOptionalViews{
    __weak  typeof(self)weakSelf = self;
    [self.view addSubview:self.cameraBottomView];
    [self.cameraBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.mas_equalTo(weakSelf.view);
        make.height.mas_equalTo(90.f);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).with.offset(-44);
    }];
    for (int i =0; i < self.items.count; i++) {
        UIButton * item  = [UIButton buttonWithType:UIButtonTypeCustom];
        item.layer.masksToBounds = YES;
        item.layer.cornerRadius = 35/2.f;
        [item setTitle:self.items[i] forState:UIControlStateNormal];
        [item setBackgroundColor:UIColorFromRGB(0x797979)];
        [item.titleLabel setFont:[UIFont systemFontOfSize:9.f]];
        [item addTarget:self action:@selector(photoOptionalWithType:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:item];
        [self.itemContainers addObject:item];
    }
}

-(void)viewlayoutSubViews{
    __weak  typeof(self)weakSelf = self;
    __block UIButton * anchor = nil;
    void (^AnimationBlock)(UIButton *) = ^(UIButton* item){
        [item mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(35, 35));
        make.right.mas_equalTo(weakSelf.view.mas_right).with.offset(-10.f);
            if (anchor == nil) {
        make.top.mas_equalTo(weakSelf.mas_topLayoutGuide).with.offset(20.f);
            }else
            {
            make.top.mas_equalTo(anchor.mas_bottom).with.offset(15.f);
            }
        }];
    };
    void (^AnimationCompleteBlock)(UIButton *) = ^(UIButton* item){
        [item mas_updateConstraints:^(MASConstraintMaker *make) {
            if (anchor == nil) {
            make.top.mas_equalTo(weakSelf.mas_topLayoutGuide).with.offset(20.f);
            }else
            {
            make.top.mas_equalTo(anchor.mas_bottom).with.offset(20.f);
                
            }
        }];
    };
    
    [self.itemContainers enumerateObjectsUsingBlock:^(UIButton*  _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
        AnimationBlock(item);
        [UIView animateWithDuration:0.2 * idx delay:0.2 * idx options:UIViewAnimationOptionTransitionNone animations:^{
            AnimationCompleteBlock(item);
            anchor = item;
            [weakSelf.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            
        }];
    }];
}
-(CameraBottomView *)cameraBottomView{
    _cameraBottomView = ({
        if (!_cameraBottomView) {
            __weak  typeof(self)weakSelf = self;
            _cameraBottomView = [[CameraBottomView alloc]init];
            _cameraBottomView.handler = ^(UIButton*args){
                if (args.tag == 1000) {
                    [weakSelf photoFromSessionStartRunning];
                }else if (args.tag == 1001){
                    [QKEasyAlbumController showAlblumWithController:weakSelf maxNumber:6 minNumuber:1 finish:^(BOOL chosed, NSMutableArray<UIImage *> *assets) {
                        
                    }];
                    
                }else{
                    [weakSelf switchCaptureFrontOrBack];
                }
            };
        }
        _cameraBottomView;
    });
    return _cameraBottomView;
}

-(NSMutableArray *)itemContainers{
    _itemContainers = ({
        if (!_itemContainers) {
            _itemContainers = [NSMutableArray array];
        }
        _itemContainers;
    });
    return _itemContainers;
}

-(NSMutableArray *)items{
    _items = ({
        if (!_items) {
            _items = [NSMutableArray array];
            NSArray * opts = @[@"闪光灯",@"对焦",@"曝光",@"白平衡",@"手电筒"];
            for (int i = 0; i < opts.count; i++) {
                NSString * title = [NSString stringWithFormat:@"%@",opts[i]];
                [_items addObject:title];
            }
        }
        _items;
    });
    return _items;
}


-(UIImageView *)imageView{
    _imageView = ({
        if (!_imageView) {
            _imageView = [[UIImageView alloc]init];
            _imageView.frame = CGRectMake(0, (64+20), KScreenWidth, KScreenHeight - (44 +64+20));
        }
        _imageView;
    });
    return _imageView;
}

-(AVCaptureDevice*)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray * devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ){
            return device;
        }
    return nil;
}

-(void)cameraConfiguation{
    self.captureDevice = [self cameraWithPosition:AVCaptureDevicePositionFront];
    NSError * _error = nil;
    self.input=  [[AVCaptureDeviceInput alloc]initWithDevice:self.captureDevice error:&_error];
    self.imageOutput = [[AVCaptureStillImageOutput alloc]init];
    self.session = [[AVCaptureSession alloc]init];
    /*
     //    拿到的图像的大小可以自行设定
     //    AVCaptureSessionPreset320x240
     //    AVCaptureSessionPreset352x288
     //    AVCaptureSessionPreset640x480
     //    AVCaptureSessionPreset960x540
     //    AVCaptureSessionPreset1280x720
     //    AVCaptureSessionPreset1920x1080
     //    AVCaptureSessionPreset3840x2160
    */
    self.session.sessionPreset = AVCaptureSessionPreset640x480;
    //输入输出设备结合
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.imageOutput]) {
            [self.session addOutput:self.imageOutput];
    }
    //预览层生成
    self.videoPreviewPlayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.videoPreviewPlayer.frame = CGRectMake(0,(0), KScreenWidth, KScreenHeight-(0+44+90));
    self.videoPreviewPlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.videoPreviewPlayer];
    //设备取景开始
    [self.session startRunning];
    if ([_captureDevice lockForConfiguration:nil]) {
        //自动闪光灯，
        if ([_captureDevice isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_captureDevice setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡,但是好像一直都进不去
        if ([_captureDevice isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_captureDevice setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_captureDevice unlockForConfiguration];
    }
}
//判断是否有多个摄像头
-(BOOL)hasMutipleCameras{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    if (devices != nil && [devices count] > 1) return YES;
    return NO;
}
#pragma 前后置摄像头切换
-(void)switchCaptureFrontOrBack{
   
    if ([self hasMutipleCameras] == NO)return;
    NSArray *inputs = self.session.inputs;
    for (AVCaptureDeviceInput * captureDeviceInput in inputs) {
        AVCaptureDevice * device = captureDeviceInput.device;
        if ([device hasMediaType:AVMediaTypeVideo]) {
            AVCaptureDevicePosition  position = device.position;
            AVCaptureDevice *newCamera = nil ;
            AVCaptureDeviceInput *newInput = nil ;
            if (position == AVCaptureDevicePositionFront) {
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            }else{
                newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            }
            NSError * _error = nil;
            newInput=  [[AVCaptureDeviceInput alloc]initWithDevice:newCamera error:&_error];
            [self.session beginConfiguration];
            [self.session removeInput:captureDeviceInput];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
            }
            [self.session commitConfiguration];
        }
    }
    
}
#pragma 开启闪光灯
-(void)processCaptureFlash{
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device.flashMode == AVCaptureFlashModeOff) {
        if ([device hasFlash]&&[device isFlashModeSupported:AVCaptureFlashModeOn]) {
            [device lockForConfiguration:nil];
            [device setFlashMode:AVCaptureFlashModeOn];
            [device unlockForConfiguration];
        }
    }else if (device.flashMode == AVCaptureFlashModeOn){
        if ([device isFlashModeSupported:AVCaptureFlashModeOff]) {
            [device lockForConfiguration:nil];
            [device setFlashMode:AVCaptureFlashModeOff];
            [device unlockForConfiguration];
        }
    }
}

-(void)processCaptureTorch{
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device.torchMode == AVCaptureTorchModeOff) {
        if ([device isTorchModeSupported:AVCaptureTorchModeOn]) {
            [self.session beginConfiguration];
            [device lockForConfiguration:nil];
            [device setTorchMode:AVCaptureTorchModeOn];
            [device unlockForConfiguration];
            [self.session commitConfiguration];
            [self.session startRunning];
        }
    }else if (device.torchMode == AVCaptureTorchModeOn){
        [self.session beginConfiguration];
        [device lockForConfiguration:nil];
        [device setTorchMode:AVCaptureTorchModeOff];
        [device unlockForConfiguration];
        [self.session commitConfiguration];
        [self.session startRunning];
    }
}

#pragma mark 对焦模式
-(void)processCaptureFocus{
    
}
#pragma mark - 曝光
-(void)processCaptureExposure{
    
}
#pragma mark - 白平衡
-(void)processWhiteBalance{
    
}
-(void)photoOptionalWithType:(UIButton*)args{
    NSDictionary * param = @{@"切换":@"switchCaptureFrontOrBack",
                             @"闪光灯":@"processCaptureFlash",
                             @"对焦":@"processCaptureFocus",
                             @"曝光":@"processCaptureExposure",
                             @"白平衡":@"processWhiteBalance",
                             @"手电筒":@"processCaptureTorch"
                             };
    if ([[param allKeys]containsObject:args.currentTitle]) {
        NSString * selectorName = param[args.currentTitle];
        SEL selectors = NSSelectorFromString(selectorName);
        if ([self respondsToSelector:selectors]) {
            [self performSelector:selectors];
        }
        return;
    }
}

//拍照拿到相应图片
-(void)photoFromSessionStartRunning{
    AVCaptureConnection * connection = [self.imageOutput connectionWithMediaType:AVMediaTypeVideo];
    if (connection == nil) {
        NSLog(@"拍照失败");
        return;
    }
    [self.imageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef  _Nullable imageDataSampleBuffer, NSError * _Nullable error) {
       
        NSData * imgData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        self.image = [UIImage imageWithData:imgData];
        [self.session stopRunning];
        [self.view addSubview:self.imageView];
    }];
}
-(void)saveImageToPhotoAlbum{
    self.image = self.image ? self.image : nil;
    if (self.image == nil) return;
    UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
// 指定回调方法
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
        [self.session startRunning];
         self.image = nil;
        [self.imageView removeFromSuperview];
    }
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"保存图片成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
